<?php

namespace app\api\controller;

use app\attachment\controller\ApiUpload;
use app\common\controller\ApiBase;
use app\Constant\ApiConstant;
use think\facade\Request;

/*
 * 文件上传
 */

class Upload extends ApiBase
{
    /**
     * 上传资源
     * @param string $param 表单字段
     * @return mixed
     */
    public function upload($param = 'file')
    {
        $files  = Request::file($param);
        $upload = new ApiUpload();
        $return = [];

        if ($files) {
            try {
                if (is_array($files)) {
                    foreach ($files as $file) {
                        $res = $upload->upload($file);
                        if ($res['code'] == 0) {
                            $return[] = $res['path'];
                        }
                    }
                } else {
                    $res = $upload->upload($files);
                    if ($res['code'] == 0) {
                        $return[] = $res['path'];
                    }
                }
                return $this->callback(ApiConstant::SUCCESS, 'success', $return);
            } catch (\Exception $e) {
                $log = [
                    'message' => $e->getMessage(),
                    'line'    => $e->getLine(),
                    'file'    => $e->getFile(),
                ];
                return $this->callback(ApiConstant::FAILURE, $e->getMessage(), $log);
            }
        }

    }
}
